package server;

import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String,HttpServlet> servletMap;
    private Map<String,String> contextMap;
    private Mapper mapperElement;

    public RequestProcessor(Socket socket, Mapper mapperElement,  Map<String, String> contextMap, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
        this.contextMap = contextMap;
        this.mapperElement = mapperElement;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String content = "";
            // 根据url派发到不同的web应用
            String[] split = request.getUrl().split("/");
            String context = "/" + split[1];
            Mapper.MappedHost localhost = mapperElement.hostMap.get("localhost");
            if(!localhost.contextMap.containsKey(context)){
                response.outputHtml(request.getUrl());
            }else {
                Mapper.MappedContext mappedContext = localhost.contextMap.get(context);
                Object obj = mappedContext.obj;
                Method[] methods = obj.getClass().getMethods();
                for(Method method : methods){
                    System.out.println(method.getName());
                    if(method.getName().equals("get")){
                        content = method.invoke(obj).toString();
                    }
                }
            }
            response.output((HttpProtocolUtil.getHttpHeader200(content.getBytes().length) + content));

//            // 静态资源处理
//            if(servletMap.get(request.getUrl()) == null) {
//                response.outputHtml(request.getUrl());
//            }else{
//                // 动态资源servlet请求
//                HttpServlet httpServlet = servletMap.get(request.getUrl());
//                httpServlet.service(request,response);
//            }
            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
